﻿using System;
using System.Linq;
using Microsoft.Practices.Unity;
using WebShop.Contracts;
using WebShop.DAL.Interfaces;
using Webdiyer.WebControls.Mvc;

namespace WebShop.DAL.Repositories
{
    public class LogRepository : ILogRepository
    {
        [Dependency]
        public NWData Db { get; set; }

        public void Add(Exception ex, String userName = null, Boolean isServerError = true)
        {
            User user = null;
            if (userName != null)
            {
                user = Db.DataContext.Users.FirstOrDefault(us => us.UserName == userName);
            }

            LogItem l = new LogItem() { Time = DateTime.Now, User = user, EventTypeId = (isServerError ? 2 : 1), Description = ex.Message + "\n\r" + ex.StackTrace };
            Db.DataContext.Log.Add(l);
            Db.DataContext.SaveChanges();
        }

        public void Add(string description, String userName = null, Boolean isServerError = false)
        {
            User user = null;
            if (userName != null)
            {
                user = Db.DataContext.Users.FirstOrDefault(us => us.UserName == userName);
            }
            LogItem l = new LogItem() { Time = DateTime.Now, User = user, EventTypeId = (isServerError ? 2 : 1), Description = description };
            Db.DataContext.Log.Add(l);
            Db.DataContext.SaveChanges();
        }

        public PagedList<LogItem> List(int? page, int? pageSize)
        {
            return Db.DataContext.Log.OrderByDescending(l => l.Time).ToPagedList(page.GetValueOrDefault(1), pageSize.GetValueOrDefault(10));
        }

        public LogItem Get(Int64? id)
        {
            return Db.DataContext.Log.Find(id);
        }
    }
}